package com.cn.ZhiKeDianShang.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.ZhiKeDianShang.AppConfig;
import com.cn.ZhiKeDianShang.R;
import com.cn.ZhiKeDianShang.adapter.TasksBeanAdapter;
import com.cn.ZhiKeDianShang.base.BaseFragment;
import com.cn.ZhiKeDianShang.model.event.refushBean;
import com.cn.ZhiKeDianShang.model.response.hesuanBean;
import com.cn.ZhiKeDianShang.model.response.oderLiist;
import com.cn.ZhiKeDianShang.presenter.MineFragmentPresenter;
import com.cn.ZhiKeDianShang.presenter.view.MineFragmentView;
import com.cn.ZhiKeDianShang.ui.activity.OrderDetailActivity;
import com.cn.ZhiKeDianShang.util.LogUtil;
import com.cn.ZhiKeDianShang.util.PrefShare;
import com.cn.ZhiKeDianShang.util.ProgressDialogFragment;
import com.cn.ZhiKeDianShang.util.ToastUtil;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.HttpUtils;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.ObjectResult;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.Result;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.functions.Consumer;
import okhttp3.Call;

/**
 * Created by chengaofu on 2017/6/21.
 */

public class OrderListFragment extends BaseFragment<MineFragmentView, MineFragmentPresenter> implements MineFragmentView {


    @BindView(R.id.rc_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.fragment_list_swip)
    SwipeRefreshLayout fragmentListSwip;
    @BindView(R.id.rl_image_text)
    RelativeLayout rlImageText;
    Unbinder unbinder;
    @BindView(R.id.tv_benjin)
    TextView tvBenjin;
    @BindView(R.id.tv_zhifu)
    TextView tvZhifu;
    @BindView(R.id.tv_hesuan)
    TextView tvHesuan;

    @BindView(R.id.ll_empty)
    RelativeLayout ll_empty;


    private ProgressDialogFragment mProgressDialog;
    //    0 是今日任务  1是历史任务
    int type = 0;
    int currentPage = 1;
    int pageNumber = 10;
    //上拉加载  还有没有数据
    boolean isHaveDate = true;

    //
    private List<oderLiist.TasksBean> mVideoList = new ArrayList<>();
    private TasksBeanAdapter myLikeFreagmentAdapter;


    public static OrderListFragment getInstance(int type) {
        OrderListFragment fragment = new OrderListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected void initViewsAndEvents() {
        Bundle arguments = getArguments();
        type = arguments.getInt("type");
        fragmentListSwip.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = 1;
                getData();
            }
        });

        initRecyclerView();
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                //得到当前显示的最后一个item的view
                View lastChildView = recyclerView.getLayoutManager().getChildAt(recyclerView.getLayoutManager().getChildCount() - 1);
                if (lastChildView != null) {
                    //得到lastChildView的bottom坐标值
                    int lastChildBottom = lastChildView.getBottom();
                    //得到Recyclerview的底部坐标减去底部padding值，也就是显示内容最底部的坐标
                    int recyclerBottom = recyclerView.getBottom() - recyclerView.getPaddingBottom();
                    //通过这个lastChildView得到这个view当前的position值
                    int lastPosition = recyclerView.getLayoutManager().getPosition(lastChildView);

                    //判断lastChildView的bottom值跟recyclerBottom是否相等
                    //判断lastPosition是不是最后一个position
                    if (lastChildBottom == recyclerBottom && lastPosition == recyclerView.getLayoutManager().getItemCount() - 1) {
                        ToastUtil.showShort("滑动到底部了");
                        if (isHaveDate) {
                            currentPage++;
                            getData();
                        }
                    }
                }
            }
        });
        getData();

    }

    private void initRecyclerView() {
        myLikeFreagmentAdapter = new TasksBeanAdapter(getActivity(), R.layout.item_video_like, mVideoList, new TasksBeanAdapter.onItemClick() {
            @Override
            public void onItemClick(int position) {
//                ToastUtil.showShort("点击事件" + position);
                initPermission(position);
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(myLikeFreagmentAdapter);
    }


    private void initPermission(int position) {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(
                Manifest.permission.ACCESS_COARSE_LOCATION
                , Manifest.permission.ACCESS_FINE_LOCATION
                , Manifest.permission.READ_PHONE_STATE
        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    Intent intent = new Intent(getActivity(), OrderDetailActivity.class);
                    intent.putExtra("taskid", mVideoList.get(position).getId() + "");
                    intent.putExtra("type", type);
                    startActivity(intent);
                } else {
                    //只要有一个权限被拒绝，就会执行
                    Toast.makeText(getActivity(), "未授权权限，部分功能不能使用", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    /**
     * @param
     */
    private void getData() {
//        DialogHelper
        String token = PrefShare.getInstance(getActivity()).getString("token");
        String userId = PrefShare.getInstance(getActivity()).getString("userId");
        Map<String, String> params = new HashMap<>();
        params.put("token", token);
        params.put("userid", userId);
        params.put("page", currentPage + "");
        params.put("pagesize", pageNumber + "");
        String url = "";
        if (type == 0) {
            //今日数据
            url = AppConfig.OERDER_TODAY;
        } else {
            //历史数据
            url = AppConfig.ORDER_HISTORY;
        }

        HttpUtils.post().url(url)
                .params(params)
                .build()
                .execute(new BaseCallback<oderLiist>(oderLiist.class) {
                    @Override
                    public void onResponse(ObjectResult<oderLiist> result) {
                        try {
                            if (Result.checkSuccess(getActivity(), result)) {
                                oderLiist data = result.getData();
                                if (currentPage == 1) {
                                    myLikeFreagmentAdapter.setData(data.getTasks());
                                    if (data.getTasks().size() == 0) {
                                        ll_empty.setVisibility(View.VISIBLE);
                                    } else {
                                        ll_empty.setVisibility(View.GONE);
                                    }
                                } else {
                                    ll_empty.setVisibility(View.GONE);
                                    myLikeFreagmentAdapter.addAll(data.getTasks());
                                }
                                //所返回的数据个数 没有pageNumber 个的  说明已经没有数据了
                                if (data.getTasks().size() != pageNumber) {
                                    isHaveDate = false;
                                } else {
                                    isHaveDate = true;
                                }
                                mVideoList = myLikeFreagmentAdapter.getAll();
                                LogUtil.d("Debug", "当前的mVideoList个数为" + mVideoList.size());
                                myLikeFreagmentAdapter.notifyDataSetChanged();
                            }
                            if (fragmentListSwip != null) {
                                fragmentListSwip.setRefreshing(false);
                            }
                        } catch (Exception E) {

                        }

                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        if (fragmentListSwip != null) {
                            fragmentListSwip.setRefreshing(false);
                        }
                    }
                });

    }


    /**
     * @param
     */
    private void checkMoney() {
        Map<String, String> params = new HashMap<>();
        HttpUtils.post().url(AppConfig.ORDER_ACCOUNTING)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<hesuanBean>(hesuanBean.class) {
                    @Override
                    public void onResponse(ObjectResult<hesuanBean> result) {
                        try {
                            if (Result.checkSuccess(getActivity(), result)) {
                                hesuanBean data = result.getData();
                                tvZhifu.setText("实际总支付：" + data.getPay());
                                tvBenjin.setText("任务总本金：" + data.getZje());
                            }
                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                    }
                });

    }


    private void supportRequestWindowFeature(int featureActionBarOverlay) {
    }


    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    protected int getErrorLayoutId() {
        return R.layout.ordlist_layout;
    }

    @Override
    protected int getNormalLayoutId() {
        return R.layout.ordlist_layout;
    }

    @Override
    protected MineFragmentPresenter createPresenter() {
        return new MineFragmentPresenter(getContext(), this);
    }


    @Override
    public void requestFailed(String message) {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        EventBus.getDefault().register(this);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setMessageEvent(refushBean messageEvent) {
        Log.d("Debug", "接受到通知-----" + messageEvent.getPosition());
        currentPage = 1;
        getData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

    }


    @OnClick({R.id.tv_zhifu, R.id.tv_hesuan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_zhifu:
                break;
            case R.id.tv_hesuan:
                checkMoney();
                break;
        }
    }
}